﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using AutoMapper;
using SapaFinance.DTO;
using SapaFinance.Domain.Model;
using SapaFinance.GenericRepository;

namespace SapaFinance.Services
{
    public interface ICurrencyService
    {
        IEnumerable<SelectListItem> GetSelectedListById(Guid id);
        Currency GetCurrency(Guid id);
        IEnumerable<CurrencyDTO> GetListDTO();
        void Update(CurrencyDTO dto);
    }

    public class CurrencyService : ICurrencyService
    {
        private readonly IGenericRepository<Currency, Guid> _currencyRepository;
        private readonly IMappingEngine _mappingEngine;
        private readonly IUnitOfWork _unitOfWork;

        public CurrencyService(IGenericRepository<Currency,Guid> currencyRepository, IMappingEngine mappingEngine, IUnitOfWork unitOfWork)
        {
            _currencyRepository = currencyRepository;
            _mappingEngine = mappingEngine;
            _unitOfWork = unitOfWork;
        }

        #region ICurrencyService Members

        public IEnumerable<SelectListItem> GetSelectedListById(Guid id)
        {
            return Guid.Empty.Equals(id)
                       ? _mappingEngine.Map<IEnumerable<Currency>, IEnumerable<SelectListItem>>(_currencyRepository.GetAll())
                       : _mappingEngine.Map<Currency, IEnumerable<SelectListItem>>(_currencyRepository.GetById(id));
        }

        public Currency GetCurrency(Guid id)
        {
            return _currencyRepository.GetById(id);
        }

        public IEnumerable<CurrencyDTO> GetListDTO()
        {
            return _mappingEngine.Map<IEnumerable<Currency>, IEnumerable<CurrencyDTO>>(_currencyRepository.GetAll());
        }


        public virtual void Update(CurrencyDTO dto)
        {
            var entity = _currencyRepository.GetById(dto.UID);
            entity.Name = dto.Name;
            _currencyRepository.Update(entity);
            _unitOfWork.Flush();
        }
        #endregion
    }
}